package com.example.yls.work_wuziqi;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yls on 2018/6/13.
 */

public class WuziPanel extends View{
    private int panelWidth;                          //画板的宽度
    private float itemSize;                          //格子宽度
    private int MAX_COUNT_IN_LINE = 5;              //棋子胜利的个数
    private static final int MAX_ITEMS=10;         //格子的个数
    private Paint paint;                              //画笔
    private Bitmap mWhitePiece;                      //白棋
    private Bitmap mBlackPiece;                      //黑棋
    private float ratioPieceOfLineHeight = 3 * 1.0f/4;  // 旗子是行高四分三
    public boolean mIsWhite = true;                      //白棋先手
    public ArrayList<Point> mWhiteArray = new ArrayList<>();   //储存白点
    public  ArrayList<Point> mBlackArray = new ArrayList<>();   //储存黑点
    public boolean mIsGameOver;
    public boolean mIsWhiteWinner;
    public WuziPanel(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    /*
    * 初始化数据
    * */
    private void init() {
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        mWhitePiece = BitmapFactory.decodeResource(getResources(),R.drawable.stone_w2);
        mBlackPiece = BitmapFactory.decodeResource(getResources(),R.drawable.stone_b1);
    }
    /*
    * 画出棋盘
    * */
    private void drawBoard(Canvas canvas) {
        for(int i=0;i<MAX_ITEMS;i++){
            int startX=(int)(itemSize/2);
            int endX = (int)(panelWidth - (itemSize/2));
            int y = (int)(((0.5f+i)*itemSize));
            canvas.drawLine(startX,y,endX,y,paint);
            canvas.drawLine(y,startX,y,endX,paint);
        }
    }
    /*
    * 测量宽高数据
    * */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int result = Math.min(width,height);
        setMeasuredDimension(result,result);
    }
    /*
    * 屏幕大小改变时画板跟着改变
    * */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        panelWidth = w;
        itemSize = panelWidth * 1.0f / MAX_ITEMS;
        int pieceWidth = (int)(itemSize * ratioPieceOfLineHeight);
        mWhitePiece = Bitmap.createScaledBitmap(mWhitePiece,pieceWidth,pieceWidth,false);
        mBlackPiece = Bitmap.createScaledBitmap(mBlackPiece,pieceWidth,pieceWidth,false);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mIsGameOver){
            return false;
        }
        Log.e("aaa","触摸事件");
        int action = event.getAction();
        if(action == MotionEvent.ACTION_DOWN){
            int x = (int)event.getX();
            int y = (int)event.getY();
            Point p = getValidPoint(x,y);
            if(mWhiteArray.contains(p) || mBlackArray.contains(p)){
                return false;
            }
            if(mIsWhite){
                Log.e("aaa","白棋");
                mWhiteArray.add(p);

            }else{
                Log.e("aaa","黑棋");
                mBlackArray.add(p);

            }
            invalidate();
            mIsWhite = !mIsWhite;
            return true;
        }
        return super.onTouchEvent(event);
    }

    private Point getValidPoint(int x, int y) {
        Log.e("aaa","下子:("+(int)(x/itemSize)+","+(int)(y/itemSize)+")");
        return  new Point((int)(x/itemSize),(int)(y/itemSize));
    }
    /*
    * 画棋子
    * */
    private void drawPieces(Canvas canvas) {
        for(int i = 0,n = mWhiteArray.size();i<n;i++){
            Point whitePoint = mWhiteArray.get(i);
            canvas.drawBitmap(mWhitePiece,
                    (whitePoint.x+(1 - ratioPieceOfLineHeight)/2)*itemSize,
                    (whitePoint.y+(1 - ratioPieceOfLineHeight)/2)*itemSize,
                    null
                    );
        }
        for(int i = 0,n = mBlackArray.size();i<n;i++){
            Point blackPoint = mBlackArray.get(i);
            canvas.drawBitmap(mBlackPiece,
                    (blackPoint.x+(1 - ratioPieceOfLineHeight)/2)*itemSize,
                    (blackPoint.y+(1 - ratioPieceOfLineHeight)/2)*itemSize,
                    null
            );
        }
    }
    /*
        * 画出内容
        * */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        drawPieces(canvas);
        checkGameOver();
    }

    private void checkGameOver() {
        boolean whiteWin = checkFiveInLine(mWhiteArray);
        boolean blackWin = checkFiveInLine(mBlackArray);
        if(whiteWin || blackWin){
            mIsGameOver = true;
            mIsWhiteWinner = whiteWin;
            String text = mIsWhiteWinner ? "白棋胜利" : "黑棋胜利";
            Toast.makeText(getContext(),text,Toast.LENGTH_SHORT).show();
        }
    }

    private boolean checkFiveInLine(List<Point> points) {
        for(Point p : points){
            int x = p.x;
            int y = p.y;
           boolean win = checkAll(x,y,points,-1,0,1,0);
            if(win) return true;
           win = checkAll(x,y,points,0,-1,0,1);
            if(win) return true;
           win = checkAll(x,y,points,-1,1,1,-1);
            if(win) return true;
           win = checkAll(x,y,points,-1,-1,1,1);
            if(win) return true;
        }
        return false;
    }
    private boolean checkAll(int x, int y, List<Point> points,int n1,int n2,int n3,int n4) {
        int count = 1 ;
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x+i*n1,y+i*n2))){
                count++;
            }else {
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE){
            return true;
        }
        for(int i=1;i<MAX_COUNT_IN_LINE;i++){
            if(points.contains(new Point(x+i*n3,y+i*n4))){
                count++;
            }else{
                break;
            }
        }
        if(count==MAX_COUNT_IN_LINE){
            return true;
        }
        return false;
    }
    private static final String INSTANCE = "instance";
    private static final String INSTANCE_GAME_OVER = "instance_game_over";
    private static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
    private static final String INSTANCE_BLACK_ARRAY = "instance_blace_array";
    @Nullable
    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE,super.onSaveInstanceState());
        bundle.putBoolean(INSTANCE_GAME_OVER,mIsGameOver);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY,mWhiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY,mBlackArray);
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if(state instanceof Bundle){
            Bundle bundle = (Bundle)state;
            mIsGameOver = bundle.getBoolean(INSTANCE_GAME_OVER);
            mWhiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            mBlackArray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
            super.onRestoreInstanceState(bundle.getBundle(INSTANCE));
            return;
        }
        super.onRestoreInstanceState(state);
    }
    public void start(){
        mWhiteArray.clear();
        mBlackArray.clear();
        mIsWhite = true;
        mIsGameOver = false;
        mIsWhiteWinner = false;
        invalidate();
    }
    public void lastView(){
        if(!mIsGameOver){
            if(!mIsWhite){
                if(mWhiteArray.size()>0){
                    mWhiteArray.remove(mWhiteArray.size()-1);
                    mIsWhite = !mIsWhite;
                }
            }else{
                if(mBlackArray.size()>0){
                    mBlackArray.remove(mBlackArray.size()-1);
                    mIsWhite = !mIsWhite;
                }
            }
            if(mWhiteArray.size()<=0 & mBlackArray.size()<=0){
                start();
            }
            invalidate();
        }else {
            if(mIsWhiteWinner){
                Toast.makeText(getContext(),"白棋已赢不得悔棋",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(getContext(),"黑棋已赢不得悔棋",Toast.LENGTH_SHORT).show();
            }
        }
    }
}
